#include <linux/time.h>
#include <linux/slab.h>
#include <linux/ip.h>
#include "log.h"
#include "memory.h"
#include "fw5.h"

static logFile_t log;	// Log array global variable

static int initLog(void){
	// allocate memory for rows
	log.rows = allocateMemory(LOG_MAX_BYTES);
	if(log.rows == NULL){
		//allocation failed
		return 0;
	}
	memset(log.rows,0,LOG_MAX_BYTES);
	log.size = 0;
	return 1;
}

static int writeLog(unsigned int src_ip, unsigned int dst_ip, unsigned short src_port, unsigned short dst_port, unsigned char protocol, unsigned char action, signed int reason, unsigned char hooknum, unsigned char stringIndex){
	int i;
	//Do not log localhost communication
	if(src_ip == ntohl(LOCALHOST) || dst_ip == ntohl(LOCALHOST)){		
		return 0;
	}
	for(i=0;i<log.size;++i){
		//check both sides of conversation
		if((log.rows[i].src_ip == src_ip && log.rows[i].dst_ip == dst_ip && log.rows[i].src_port == src_port && log.rows[i].dst_port == dst_port) || 
			(log.rows[i].src_ip == dst_ip && log.rows[i].dst_ip == src_ip && log.rows[i].src_port == dst_port && log.rows[i].dst_port == src_port)){
			if(log.rows[i].protocol == protocol && log.rows[i].action == action && log.rows[i].reason == reason && log.rows[i].hooknum == hooknum){
				//Found a previous entry
				log.rows[i].count++;
				log.rows[i].modified = get_seconds();
				log.rows[i].offset = stringIndex;
				break;
			}
		}
	}
	if(i == log.size){
		//entry not found, insert a new entry
		if(log.size + 1 >= LOG_ENTRIES){
			//cannot add more to log
			 return 0;
		}
		log.rows[i].src_ip = src_ip;
		log.rows[i].dst_ip = dst_ip;
		log.rows[i].src_port = src_port;
		log.rows[i].dst_port = dst_port;
		log.rows[i].protocol = protocol;
		log.rows[i].action = action;
		log.rows[i].reason = reason;
		log.rows[i].hooknum = hooknum;
		log.rows[i].count = 1;
		log.rows[i].modified = get_seconds();
		log.rows[i].offset = stringIndex;
		log.size++;
	}
	return 1;
}

static void clearLog(void){
	memset(log.rows,0,LOG_MAX_BYTES);
	log.size = 0;
}

//For debugging
/*static void printLog(void){
	int i;
	__be32 s,d;
	for(i=0;i<log.size;++i){
		s = htonl(log.rows[i].src_ip);
		d = htonl(log.rows[i].dst_ip);
		printk("Log Entry %d: src_ip %pI4, dst_ip %pI4, count %d, modifed %d action %d\n",i,&s,&d,log.rows[i].count,log.rows[i].modified,log.rows[i].action);
	}
}*/
